import React, { useRef, useState, useMemo } from 'react';
import { FilterTwoTone, HeartTwoTone } from '@ant-design/icons';
import { Layout, Menu, theme } from 'antd';
import { BigTicketScreening } from './pages/BigTicketScreening';
import { SubscriptionList } from './pages/SubscriptionList';

const { Sider, Content } = Layout;

// 将 AppSider 移到外部
function AppSider({ onSider_select, pageItems }) {
  return (
    <Sider
      trigger={null}
      style={{
        height: '100vh',
        position: 'sticky',
        top: 0,
        bottom: 0,
      }}
    >
      <Menu
        onSelect={onSider_select}
        theme="dark"
        defaultSelectedKeys={['0']}
        items={pageItems}
      />
    </Sider>
  );
}

export default function APP() {
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 定义 ref 来保存页面数据
  const bigTicketScreeningRef = useRef(null);
  const subscriptionListRef = useRef(null);

  // 使用 useMemo 优化 PageItems 的定义
  const pageItems = useMemo(
    () => [
      {
        key: '0',
        icon: <FilterTwoTone />,
        label: '大票筛选',
      },
      {
        key: '1',
        icon: <HeartTwoTone />,
        label: '订阅列表',
      },
    ],
    []
  );

  // 定义页面组件
  const pages = useMemo(
    () => ({
      0: <BigTicketScreening key="0" ref={bigTicketScreeningRef} />,
      1: <SubscriptionList key="1" ref={subscriptionListRef} />,
    }),
    []
  );

  const [currentPageIndex, setCurrentPageIndex] = useState(0);

  const onSider_select = ({ key }) => {
    setCurrentPageIndex(Number(key)); // 将 key 转换为数字类型
  };

  return (
    <Layout hasSider>
      <AppSider onSider_select={onSider_select} pageItems={pageItems} />
      <Layout>
        <Content
          style={{
            margin: '8px 8px',
            overflow: 'initial',
          }}
        >
          <div
            style={{
              padding: 8,
              textAlign: 'center',
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            {/* 使用条件渲染保留页面状态 */}
            {Object.entries(pages).map(([key, component]) => (
              <div key={key} style={{ display: key === currentPageIndex.toString() ? 'block' : 'none' }}>
                {component}
              </div>
            ))}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
}